package com.zjs.practice.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述
 *
 * @author zhu
 * @version 1.0
 * @date 2021/5/24 16:51
 */
@Configuration
public class ThreadPoolConfig {

    @Value("${threadPoolConfig.corePoolSize}")
    private Integer corePoolSize;

    @Value("${threadPoolConfig.maximumPoolSize}")
    private Integer maximumPoolSize;

    @Value("${threadPoolConfig.keepAliveTime}")
    private Integer keepAliveTime;

    @Value("${threadPoolConfig.blockingQueueMax}")
    private Integer blockingQueueMax;

    @Bean
    public ThreadPoolExecutor buildThreadPool() {
        // 缓冲队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(blockingQueueMax);
        // 线程工厂
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("my-thread-%d").build();
        // 拒绝策略
        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,
                threadFactory,
                rejectedExecutionHandler);
    }
}
